<?php

require_once 'classes/LightPressPlugin.php';

class TopCommented extends LightPressPlugin {

    var $constructor_args = array(
        'active_days'=>'number of days to query');
    var $default_context = LP_CONTEXT_ALL;
    var $description = 'Display the top n most commented posts';
    
    var $active = true;
    var $hooks = array('sidebar');
    
    var $active_days = 60;
    
    function TopCommented(&$frontend, $args, $dummy_run=false) {
        $this->LightPressPlugin($frontend, $args, $dummy_run);
    }
    
    function run($hook, &$hook_data) {
        $db =& $this->_frontend->db;
        $tpl =& $this->_frontend->tpl;
        $tpl->setFile('plugin_topcommented', 'plugins/top_commented.xml');
        $q = "select
                p.id as post_id, p.post_name as name, p.post_title as title,
                p.post_date as date, count(c.comment_id) as comments,
                UNIX_TIMESTAMP(p.post_date) as tstamp, p.post_category
            from " . $this->_frontend->tables['posts'] . " p 
            inner join " . $this->_frontend->tables['comments'] . " c on c.comment_post_id = p.id 
            where
                p.post_date_gmt <= '{$this->_frontend->where_date}'
                and p.post_status = 'publish' and
                c.comment_approved = '1'
            group
                by p.id, p.post_name, p.post_title, p.post_date
            order by
                comments desc, p.post_date_gmt desc limit 0, 10" ;
        $db->query($q);
        
        if ($db->count == 0) {
            $tpl->setVar('PLUGIN_TOPCOMMENTED', '');
            return;
        }
        
        $options =& $this->_frontend->options;
        
        $top_comments = array();
        $pp = $this->_frontend->options['post_prefix'];
        foreach ($db->all() as $k => $v) {
            $v['date'] = strftime($options['date_format'], $v['tstamp']);
            $v['short_date'] = strftime($options['short_date_format'], $v['tstamp']);
            $v['permalink'] = $this->_frontend->getPermalink($v['post_id'], $v['name'], $v['tstamp'], $v['post_category']);
            $v['class'] = ($k % 2 == 0) ? 'sidebar_toplist_odd' : 'sidebar_toplist_even';
            $top_comments[] = $v;
        }
        
        $tpl->parseBlock('PLUGIN_TOPCOMMENTED_COMMENT', 'plugin_topcommented_comment', $top_comments, 'plugin_topcommented');
        $tpl->setVar('plugin_topcommented_active_days', $this->active_days);
        $tpl->parse('PLUGIN_TOPCOMMENTED', 'plugin_topcommented');
    }
    
}

?>